/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.risk.bean.WeatherBean;
import com.koron.risk.util.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.GZIPInputStream;

/**
 * @Author: liaodf
 * @Date: 2021/7/6 10:55
 */

@Api(tags = "weather", description = "天气")
@RestController
@RequestMapping("/weather")
public class WeatherController {

    private final static Logger logger= LoggerFactory.getLogger(WeatherController.class);
    private static Map<String, String> map = new HashMap<>();

    @ApiOperation("获取未来5天的天气数据,默认查询珠海")
    @RequestMapping(value = "/getZhuHaiWeather.htm", method = RequestMethod.GET)
    public MessageBean<?> getZhuHaiWeather(String cityCode, String city) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, "查询天气成功", List.class);
        // 中华万年历API(数据来源于中国天气网)
//        String url = "http://wthrcdn.etouch.cn/weather_mini?";
        String url = "http://t.weather.sojson.com/api/weather/city/101280701";
//        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
//        if (StringUtils.isNotEmpty(cityCode)) {
//            //按城市编码查
//            params.add(new BasicNameValuePair("citykey", cityCode));
//        } else if (StringUtils.isNotEmpty(city)) {
//            // 按城市名称查
//            params.add(new BasicNameValuePair("city", city));
//        } else {
//            // 默认查询珠海
//            params.add(new BasicNameValuePair("citykey", "101280701"));
//            params.add(new BasicNameValuePair("city", "珠海"));
//        }
//        String param = URLEncodedUtils.format(params, "utf-8");
//        HttpGet httpGet = new HttpGet(url + param);
        Calendar calendar = Calendar.getInstance();
        List<WeatherBean> list = new ArrayList<>();
        try {
            String result = null;
            if (!map.isEmpty()) {
                String data = map.get("data");
                long timeInMillis = calendar.getTimeInMillis();
                if (timeInMillis < Long.valueOf(data)) {
                    result = map.get("result");
                }
            }
            if (StringUtils.isEmpty(result)) {
                HttpGet httpGet = new HttpGet(url);
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse httpResponse = null;
                httpResponse = httpClient.execute(httpGet);
                // 获取到解压缩之后的字符串
                result = getJsonStringFromGZIP(httpResponse);
                long time = calendar.getTimeInMillis() + 60 * 60 * 1000;
                map.put("data", String.valueOf(time));
                map.put("result", result);
            }
            if (StringUtils.isNotEmpty(result)) {
                // 输出
                JSONObject jsonObject = JSONObject.parseObject(result);
                String status = jsonObject.getString("status");
                String data = jsonObject.getString("data");
                String cityInfo = jsonObject.getString("cityInfo");
                String cityName = null;
                String cityKey = null;
                if (("200").equals(status) && StringUtils.isNotEmpty(cityInfo)) {
                    JSONObject jsonData = JSONObject.parseObject(cityInfo);
                    cityName = jsonData.getString("city");
                    cityKey = jsonData.getString("citykey");
                }
                if (("200").equals(status) && StringUtils.isNotEmpty(data)) {
                    JSONObject jsonData = JSONObject.parseObject(data);
                    String template = jsonData.getString("wendu");
                    String reminder = jsonData.getString("ganmao");
                    String forecast = jsonData.getString("forecast");
                    JSONArray array = JSONArray.parseArray(forecast);
                    for (int i = 0; i < array.size(); i++) {
                        WeatherBean bean = new WeatherBean();
                        bean.setCity(cityName);
                        bean.setCityKey(cityKey);
                        String json = array.getString(i);
                        JSONObject Object = JSONObject.parseObject(json);
                        String date = Object.getString("date");
                        int nowDay = calendar.get(Calendar.DAY_OF_MONTH);
                        int day = Integer.valueOf(date);
                        if (nowDay == day) {
                            bean.setTemplate(template);
                            bean.setReminder(reminder);
                        }
                        bean.setDate((calendar.get(Calendar.MONTH) + 1) + "月" + day + "日");
                        String week = Object.getString("week");
                        bean.setWeek(week);
                        String high = Object.getString("high");
                        bean.setHighTemplate(high.substring(2, high.length() - 1).trim());
                        String windForce = Object.getString("fl");
                        bean.setWindForce(windForce);
                        String low = Object.getString("low");
                        bean.setLowTemplate(low.substring(2, low.length() - 1).trim());
                        String type = Object.getString("type");
                        bean.setType(type);
                        String wind = Object.getString("fx");
                        bean.setWind(wind);
                        list.add(bean);
                    }
                }
            }
            msg.setData(list);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_FAIL);
            msg.setDescription("查询天气失败");
        }
        return msg;
    }


    private static String getJsonStringFromGZIP(HttpResponse response) {
        String jsonString = null;
        try {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            if (result != -1 && headerData == 0x1f8b) {
                is = new GZIPInputStream(bis);
            } else {
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return jsonString;
    }

    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }
}
